package com.skydroid.h30

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import com.skydroid.fpvlibrary.serial.SerialPortConnection
import com.skydroid.h30.utils.BusinessUtils
import com.skydroid.h30.utils.String2ByteArrayUtils
import com.zhouyou.view.seekbar.SignSeekBar
import java.io.IOException

/**
 * 获取摇杆舵量示例
 */
class RockerActivity: AppCompatActivity() {
    protected val PACKAGE_HEADER_BUF = "fengyingdianzi:".toByteArray()

    protected var mSerialPortConnection: SerialPortConnection? = null


    private var mLopperThread: LopperThread? = null

    private var mSeekBarList = ArrayList<SignSeekBar?>()

    private var mTVList = ArrayList<TextView?>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_rocker)
        initView()
        openConnect()
    }

    companion object{
        fun start(context: Context){
            context.startActivity(
                Intent(context,
                    RockerActivity::class.java)
            )
        }
    }

    private fun initView(){
        var items = intArrayOf(
            R.id.item1,
            R.id.item2,
            R.id.item3,
            R.id.item4,
            R.id.item5,
            R.id.item6,
            R.id.item7,
            R.id.item8,
            R.id.item9,
            R.id.item10,
            R.id.item11,
            R.id.item12,
            R.id.item13,
            R.id.item14,
            R.id.item15,
            R.id.item16
        )

        for (i in items){
            var item = findViewById<View>(i)
            var searchBar = item.findViewById<SignSeekBar>(R.id.search_bar)
            var tv = item.findViewById<TextView>(R.id.tv)
            mSeekBarList?.add(searchBar)
            mTVList?.add(tv)
        }

        for (v in mSeekBarList){
            v?.isClickable = false
            v?.isEnabled = false
            v?.isFocusable = false
        }
    }

    /**
     * 打开连接
     */
    private fun openConnect(){
        mSerialPortConnection = SerialPortConnection.newBuilder("/dev/ttyMSM1", 57600)
            .build()

        mSerialPortConnection?.setDelegate(object : SerialPortConnection.Delegate {
            override fun received(bytes: ByteArray, size: Int) {
                var datas = ByteArray(size)
                System.arraycopy(bytes,0,datas,0,size)
//                    LogUtils.test("received：${String2ByteArrayUtils.bytes2Hex(datas)}")
                //需要自行组包
                received(datas)
            }
            override fun connect() {
                mLopperThread = LopperThread()
                mLopperThread?.start()
            }


        })

        try {
            //打开串口
            mSerialPortConnection?.openConnection()
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    /**
     * 关闭连接
     */
    private fun closeConnect(){
        mLopperThread?.interrupt()
        mLopperThread = null
        try {
            mSerialPortConnection?.closeConnection()
        } catch (e: IOException) {
            e.printStackTrace()
        }
        mSerialPortConnection = null

    }


    fun received(datas: ByteArray?) {
        when(datas?.get(PACKAGE_HEADER_BUF.size)){
            0xB1.toByte()->{
                var length = datas[ PACKAGE_HEADER_BUF.size + 1]
                var startIndex = PACKAGE_HEADER_BUF.size + 2
                runOnUiThread{

                    var sb = StringBuilder()
                    for (index in 0 until length step 2){
                        var h = datas[ startIndex + index]
                        var l = datas[ startIndex + index + 1]
                        sb.append("CH${index +1}：")
                            .append( setSeekBar(index/2 , h , l))
                            .append("  ")

                    }
                }
            }
        }
    }



    private fun setSeekBar(index :Int, h :Byte, l :Byte) :Int{
        //ppm=sbus*5/8+874
        var bytes = byteArrayOf(0,0,h,l)
        var sbus = String2ByteArrayUtils.bytes2int(bytes)
//        var ppm = ((sbus * 5) / 8) + 874
//        LogUtils.test("h:${h}   " + "l:${l}   " + "Sbus:$sbus")
        mSeekBarList?.get(index)?.setProgress(sbus.toFloat())
        mTVList?.get(index)?.text = "CH${index +1}"
//        LogUtils.test("progress:${mSeekBarList?.get(index)?.progress}")
        return sbus
    }


    inner class LopperThread : Thread() {
        override fun run() {
            super.run()
            //发送对频指令 fengyingdianzi: + B1 + 2 +  R + 1 + SUM
            var cmd = ByteArray(PACKAGE_HEADER_BUF.size +  5)
            var count = PACKAGE_HEADER_BUF.size
            //写入帧头
            System.arraycopy(PACKAGE_HEADER_BUF,0,cmd,0,count)
            cmd[count++] = 0xB1.toByte()
            cmd[count++] = 2.toByte()
            cmd[count++] = 'R'.toByte()
            cmd[count++] = 1.toByte()
            //写入BCC SUM
            cmd[count] = BusinessUtils.getBCC(cmd)

            while (!isInterrupted()) {
                mSerialPortConnection?.sendData(cmd)
                try{
                    sleep(100)
                }catch (e: java.lang.Exception){
                    interrupt()
                    e.printStackTrace()
                }
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        closeConnect()

    }

}